﻿namespace Site2AppWP8.Modules
{
    using System;
    using Microsoft.Phone.Controls;
    using Site2AppWP8.Config;

    public class LogModule
    {
        public static void InjectSpys(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            var browser = sender as WebBrowser;

            if (browser != null)
            {
                InjectConsoleLogSpy(browser);
                InjectExceptionSpy(browser);
            }
        }

        public static void CheckForMessages(object sender, NotifyEventArgs e)
        {
            var content = e.Value.Split(new string[] { "~~" }, StringSplitOptions.None);

            if (content.Length == 2)
            {
                if (content[0].Equals("WINDOWONERROR", StringComparison.InvariantCultureIgnoreCase))
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("window.onError: arguments: {0}", content[1]));

                    return;
                }

                if (content[0].Equals("CONSOLELOG", StringComparison.InvariantCultureIgnoreCase))
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Console.log: {0}", content[1]));

                    return;
                }
            }
        }

        private static void InjectExceptionSpy(WebBrowser browser)
        {
            var scriptString = "(function() {\n" +
                                    "var onerrorWindow = window.onerror;\n" +

                                    "window.onerror = function() {\n" +
                                        "console.log('intercepted window.onerror');\n" +
                                        "window.external.notify('WINDOWONERROR~~' + JSON.stringify(arguments));\n" +
                                        "return onerrorWindow(arguments);\n" +
                                    "};\n" + // end of window.onerror override

                                "})();";

            browser.TryToRunScript(scriptString);
        }

        private static void InjectConsoleLogSpy(WebBrowser browser)
        {
            var scriptString = "(function() {\n" +
                                    "var logConsole = console.log;\n" +

                                    "console.log = function() {\n" +
                                        "window.external.notify('CONSOLELOG~~' + JSON.stringify(arguments));\n" +
                                        "logConsole.apply(this, arguments);\n" +
                                    "};\n" + // end of console.log override

                                "})();";

            browser.TryToRunScript(scriptString);
        }
    }
}
